package com.lsf.dunlian.utils.audio;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
/**
 * Created by lsf on 2018/5/10.
 */

public class UploadImageRunnable implements Runnable {
    private Handler handler=new Handler(Looper.getMainLooper());
    private String filekey;
    private File uploadFile;
    private String newFileName;
    private String urlStr;
    private UploadImage.Progress progress;
    private UploadImage.Request request;
    //记录当前已发送的文件大小
    int progressBarLength=0;
    //文件总大小
    long sumlen;
    private HashMap<String,String> params;
    public static final String BOUNDARY="*****";

    public UploadImageRunnable(String filekey,File uploadFile,String newFileName,String urlStr,UploadImage.Progress progress,UploadImage.Request request,HashMap<String,String> params){
        this.filekey=filekey;
        this.uploadFile=uploadFile;
        this.newFileName=newFileName;
        this.urlStr=urlStr;
        this.progress=progress;
        this.request=request;
        this.params=params;
    }
    @Override
    public void run() {
        try {
            StringBuilder sb = new StringBuilder();
            if (params != null) {
                for (String key : params.keySet()) {
                    sb.append("--" + BOUNDARY + "\r\n");
                    sb.append("Content-Disposition: form-data; name=\"" + key + "\"" + "\r\n");
                    sb.append("\r\n");
                    sb.append(params.get(key) + "\r\n");
                }
            }
            sb.append("--" + BOUNDARY + "\r\n");
            sb.append("Content-Disposition: form-data; name=\"" + filekey + "\"; filename=\"" + newFileName + "\"" + "\r\n");
            //sb.append("Content-Type: image/jpeg" + "\r\n");// 如果服务器端有文件类型的校验，必须明确指定ContentType
            sb.append("\r\n");
            System.out.println(sb.toString());
            byte[] headerInfo = sb.toString().getBytes("UTF-8");
            byte[] endInfo = ("\r\n--" +  BOUNDARY  + "--\r\n").getBytes("UTF-8");
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" +  BOUNDARY );
            conn.setRequestProperty("Content-Length", String.valueOf(headerInfo.length + uploadFile.length() + endInfo.length));
            conn.setDoOutput(true);
            OutputStream out = conn.getOutputStream();
            InputStream in = new FileInputStream(uploadFile);
            out.write(headerInfo);
            byte[] buf = new byte[100];
            int len;
            //文件总大小
            sumlen=uploadFile.length();
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
                progressBarLength=len+progressBarLength;
//                //进度监听
                progress.progress(progressBarLength,sumlen);
            }
            out.write(endInfo);
            in.close();
            out.close();
            if (conn.getResponseCode() == 200) {
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                final StringBuffer stringBuffer = new StringBuffer();
                String str;
                while ((str = br.readLine()) != null) {
                    stringBuffer.append(str);
                }
                System.out.println(stringBuffer.toString());
                if (stringBuffer.toString()!=null){
                    handler.post(() -> request.req(1,stringBuffer.toString()));

                }
            }else {
                handler.post(() -> request.req(0,null));
            }

        }catch (final Exception e){
            handler.post(() -> request.req(0,e.getMessage()));
            e.printStackTrace();
        }
    }
}
